package com.fenye.testflow.service.impl;

import com.fenye.testflow.model.dto.ImageDto;
import com.fenye.testflow.service.ImageService;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

@Service
public class ImageServiceImpl implements ImageService {
    @Override
    public byte[] generateImage(ImageDto imageRequest) throws IOException {
        int width = imageRequest.getWidth();
        int height = imageRequest.getHeight();
        String type = imageRequest.getType();
        String content = imageRequest.getContent();
        long size = imageRequest.getSize();

        // 创建图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 填充背景色
        g.setColor(new Color(new Random().nextInt(0xFFFFFF)));
        g.fillRect(0, 0, width, height);

        // 绘制内容文字
        g.setColor(Color.BLACK);
        g.setFont(new Font("Arial", Font.BOLD, 20));
        g.drawString(content, 10, 30);

        g.dispose();

        // 如果指定了文件大小，调整图片大小
        if (size > 0) {
            BufferedImage resizedImage = resizeImage(image, size,type);
            image = resizedImage;
        }

        // 将图片转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, type, baos);
        return baos.toByteArray();
    }

    // 调整图片大小以接近指定的字节大小
    private BufferedImage resizeImage(BufferedImage originalImage, long targetSize, String type) throws IOException {
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        BufferedImage resizedImage = originalImage;

        // 使用循环调整图像的大小
        while (true) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(resizedImage, type, baos);
            long currentSize = baos.size();

            if (currentSize <= targetSize || width <= 10 || height <= 10) {
                break; // 达到目标大小或图像太小则停止
            }

            width = (int) (width * 0.9); // 每次缩小10%
            height = (int) (height * 0.9);
            Image tmp = resizedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = resizedImage.createGraphics();
            g2d.drawImage(tmp, 0, 0, null);
            g2d.dispose();
        }

        return resizedImage;
    }

}
